//
//  UserAccount.swift
//  CXSwiftWB
//
//  Created by meidaeriOS on 2017/6/1.
//  Copyright © 2017年 meidaer. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {
    /// 令牌
    var access_token: String?
    
    /// 从授权那一刻开始，多少秒之后的过期时间
    var expires_in: Int = 0 {
        didSet {
           expires_Date = Date(timeIntervalSinceNow: TimeInterval(expires_in))
        }
    }
    
    /// 真正过期时间
    var expires_Date: Date?
    
    /// 用户ID
    var uid: String?
    
    /// 用户头像地址
    var avator_large: String?
    
    /// 用户昵称
    var screen_name: String?
    
    static var userAccount: UserAccount?
    
    init(dict: [String: Any]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    /// 当发现没有对应的key时就会调用
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    // MARK: - 外部控制的方法
    static let filePath = "userAccount.plist".cacheDir()
    
    /// 保存授权模型到文件中
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.filePath)
    }
    
    // MARK: - NSCoding
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avator_large, forKey: "avator_large")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(expires_Date, forKey: "expires_Date")
        aCoder.encode(expires_in, forKey: "expires_in")
    }
    
    /// 从文件中读取保存的授权模型
    class func loadUserAccount() -> UserAccount?
    {
        if userAccount != nil {
            return userAccount
        }
        
        // 从文件中加载
        userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: UserAccount.filePath) as? UserAccount
        
        guard let date = userAccount?.expires_Date, date.compare(Date()) == ComparisonResult.orderedDescending else {
            userAccount = nil
            return userAccount
        }
        
        return userAccount
    }
    
    class func login() -> Bool {
        return loadUserAccount() != nil
    }
    
    // 不能写extension
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
        avator_large = aDecoder.decodeObject(forKey: "avator_large") as? String
        uid = aDecoder.decodeObject(forKey: "uid") as? String
        expires_Date = aDecoder.decodeObject(forKey: "expires_Date") as? Date
        expires_in = aDecoder.decodeInteger(forKey: "expires_in")
    }
    
}


